import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken, setUserName } from '@/utils/auth'
import { getFunction } from '@/api/sys'
import store from '@/store'
import Cookies from 'js-cookie'

const user = {
  state: {
    token: getToken(),
    name: '',
    userId: '',
    avatar: '',
    roles: [],
    level: '',
    organId: '',
    organName: '',
    userType: '',
    roleTypes: [],
    permCodes: [],
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = store.getters.ossUrl + avatar
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERM_CODES: (state, permCodes) => {
      state.permCodes = permCodes
    },
    SET_ROLE_TYPES: (state, roleTypes) => {
      state.roleTypes = roleTypes
    },
    SET_ORGAN_ID: (state, organId) => {
      state.organId = organId
    },
    SET_ORGAN_NAME: (state, organName) => {
      state.organName = organName
    },
    SET_USER_TYPE: (state, userType) => {
      state.userType = userType
    },
    SET_LEVEL: (state, level) => {
      state.level = level
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password, userInfo.vrifyCode).then((res) => {
          if (res.code === 200) {
            setToken(res.$token)
            commit('SET_TOKEN', res.$token)
            resolve(res)
          } else reject(res.message)
        }).catch((res) => {
          reject(res)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        console.log('into:' + Cookies.get('level'))
        getInfo(state.token).then(res => {
          const data = res.data
          // commit('SET_ROLES', data.roles || [])
          commit('SET_NAME', data.displayName || data.realname || data.username)
          commit('SET_USERID', data.id)
          // commit('SET_AVATAR', data.headImg || '')
          commit('SET_ORGAN_ID', data.organId)
          commit('SET_ORGAN_NAME', data.organName)
          commit('SET_USER_TYPE', data.type)
          commit('SET_ROLE_TYPES', (data.roleTypes || '').split(','))
          commit('SET_PERM_CODES', (data.permCodes || '').toLowerCase().split(','))
          setUserName(data.username)
          for (let index = 0; index < data.roleTypes.length; index++) {
            const element = data.roleTypes[index]
            if (element === '2') {
              if (Cookies.get('level') != null) {
                if (Cookies.get('level') === 'true') {
                  commit('SET_LEVEL', 0)
                } else {
                  commit('SET_LEVEL', 1)
                }
              } else {
                Cookies.set('level', true)
                commit('SET_LEVEL', 0)
              }
            }
            if (element === '1') {
              Cookies.set('level', true)
              commit('SET_LEVEL', 0)
            }
            if (element === '3') {
              Cookies.set('level', false)
              commit('SET_LEVEL', 1)
            }
            Cookies.set('role', element)
          }

          getFunction({ level: Cookies.get('level') }).then(functionRes => {
            if (functionRes.code === 200) {
              resolve(functionRes.data)
            } else reject(functionRes.message)
          }).catch(e => {
            reject(e)
          })
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then((res) => {
          if (res.code === 200) {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resolve(res)
          } else reject(res.message)
        }).catch((error) => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resolve()
      })
    }
  }
}

export default user
